<template>
  <div>
    <section>
      <Form>
        <Row :gutter="15">
          <Col :span="6">
            <form-field :label-width="100" type="select" label="数据库服务器" :span="6" v-model="currentDbIndex" :datas="dbServers" />
          </Col>
          <Col :span="10">
            <label style="line-height:34px;">数据库地址：{{ dbAddress }}</label>
          </Col>
        </Row>
      </Form>
    </section>
    <panel style="margin-top: 10px;" title="数据库执行进程" type="success" :enableToggle="false">
      <template slot="extra">
        <ButtonGroup shape="circle">
          <Button type="error" icon="ios-trash" @click="obortAllProcess">终止所有</Button>
          <Button type="primary" icon="md-refresh" @click="onRefresh">刷新</Button>
        </ButtonGroup>
      </template>
      <Table :height="detailHeight / 1.6" :columns="processColumns" :data="processDatas" border stripe highlight-row />
    </panel>
    <Button style="margin-top: 10px;" v-if="showStatus == false" icon="ios-loading" type="primary" size="large" @click.native="getStatus">查看服务器状态信息</Button>
    <panel v-if="showStatus" style="margin-top: 10px;" title="数据库状态信息" type="primary" :enableToggle="false">
      <Table :height="detailHeight" :columns="statusColumns" :data="statusDatas" border stripe highlight-row />
    </panel>
  </div>
</template>

<script>
export default {
  data() {
    const self = this;

    return {
      detailHeight: 800,
      dbServers: [
        {
          value: 0,
          display: 'N/A'
        }
      ],
      currentDbIndex: 0,
      processDatas: [],
      processColumns: [
        {
          title: '序号',
          type: 'index',
          align: 'center',
          width: 70
        },
        {
          title: '进程ID',
          key: 'Id',
          width: 80
        },
        {
          title: '用户',
          key: 'User',
          width: 140
        },
        {
          title: '请求地址',
          key: 'Host',
          width: 180
        },
        {
          title: '数据库',
          key: 'db',
          width: 200
        },
        {
          title: '命令',
          key: 'Command'
        },
        {
          title: '执行时间(毫秒)',
          key: 'Time',
          width: 140
        },
        {
          title: '状态',
          key: 'State'
        },
        {
          title: '信息',
          key: 'Info'
        },
        {
          title: '操作',
          align: 'center',
          width: 120,
          render: (h, param) => {
            let item = param.row;

            if (item.CanKill) {
              return h(
                'Button',
                {
                  props: {
                    type: 'error',
                    shape: 'circle',
                    icon: 'ios-trash'
                  },
                  on: {
                    click() {
                      self.abortProcess(item.Id);
                    }
                  }
                },
                '终止'
              );
            }
          }
        }
      ],
      showStatus: false,
      statusDatas: [],
      statusColumns: [
        {
          title: '序号',
          align: 'center',
          width: 80,
          type: 'index'
        },
        {
          title: '变量',
          key: 'Variable_name'
        },
        {
          title: '名称',
          key: 'text'
        },
        {
          title: '值',
          key: 'Value'
        },
        {
          title: '变量详情',
          key: 'describe'
        }
      ]
    };
  },
  computed: {
    dbAddress() {
      this.currentDbIndex = this.currentDbIndex || 0;
      this.currentDbType = this.dbServers[this.currentDbIndex].type || 'mysql';

      return (this.dbServers[this.currentDbIndex] || { display: '-' }).display;
    }
  },
  watch: {
    currentDbIndex() {
      this.currentDbType = this.dbServers[this.currentDbIndex].type || 'mysql';

      this.onRefresh();
    }
  },
  methods: {
    getDbServers(initIndex) {
      this.$http.get('/api/mysql/servers').then(rs => {
        let index = 0;

        this.dbServers.splice(
          0,
          this.dbServers.length,
          ...rs.map(item => {
            return {
              text: item.display,
              value: index++,
              type: item.type,
              display: item.ip || item.Server
            };
          })
        );

        this.currentDbIndex = initIndex || 0;
        this.currentDbType = this.dbServers[this.currentDbIndex].type || 'mysql';

        this.onRefresh();
      });
    },
    onRefresh() {
      this.getProcessList();

      if (this.showStatus) {
        this.getStatus();
      }
    },
    obortAllProcess() {
      let ids = (this.processDatas || []).filter(p => p.CanKill).map(p => p.Id);

      if (ids.length == 0) {
        this.$Message.warning('没有需要终止的执行进程！');

        return;
      }

      this.abortProcess(ids.join(','));
    },
    getProcessList() {
      this.$http.post(`/api/${this.currentDbType || 'mysql'}/${this.currentDbIndex || 0}/processlist`).then(rs => {
        this.processDatas = rs.datas;
      });
    },
    abortProcess(id) {
      this.$Modal.confirm({
        title: '警告',
        content: `是否确定终止${this.currentDbType == 'mssql' ? 'SQL Server' : 'MySQL'}进程？`,
        onOk: () => {
          this.$http
            .post(`/api/${this.currentDbType}/${this.currentDbIndex}/killprocess`, {
              processId: id
            })
            .then(rs => {
              this.$Modal.success({
                title: '提示',
                content: '操作成功！',
                onOk: () => {
                  this.onRefresh();
                }
              });
            });
        }
      });
    },
    getStatus() {
      this.showStatus = true;
      this.$http.post(`/api/${this.currentDbType}/${this.currentDbIndex}/status`).then(rs => {
        this.statusDatas = rs.datas;
      });
    },
    ResizeDetailPanel(area) {
      this.detailHeight = area.height - 110;
    }
  },
  mounted() {
    let area = this.getClientArea();

    this.ResizeDetailPanel(area);
    this.$bus.on('windowResizeChanged', client => this.ResizeDetailPanel(client));

    this.getDbServers(parseInt(this.$route.query.dbIndex) || 0);
  },
  activated() {
    this.currentDbIndex = parseInt(this.$route.query.dbIndex) || 0;
    this.currentDbType = this.dbServers[this.currentDbIndex].type || 'mysql';

    this.onRefresh();
  }
};
</script>
